const { ccclass, property } = cc._decorator;

const instances = new WeakMap<any>();

@ccclass
export default class Singleton<T extends Singleton<T>> {
  constructor() {
    const constructor = this.constructor as new () => T;
    if (instances.has(constructor)) {
      throw new Error(`Singleton class ${constructor.name} already has an instance.`);
    }
    instances.set(constructor, this);
  }

  static getInstance<T extends Singleton<T>>(this: new () => T): T {
    const constructor = this as new () => T;
    if (!instances.has(constructor)) {
      instances.set(constructor, new constructor());
    }
    return instances.get(constructor) as T;
  }

  static destroyInstance() {
    const constructor = this as new () => any;
    instances.delete(constructor);
  }
}